package com.qiantu.phone.widget.setting;

import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.hjq.base.BaseDialog;
import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.QueryCodeResultBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static android.util.TypedValue.COMPLEX_UNIT_PX;

public class DeviceSettingCodeMatching extends SettingBar implements View.OnClickListener {

    private DeviceBean mDevice;
    private AppActivity mContext;
    private String queryCode;
    private int totalTime = 15 * 1000;
    private long startTime;

    public DeviceSettingCodeMatching(AppActivity context, DeviceBean deviceBean, String title) {
        this(context, null, deviceBean, title);
    }

    public DeviceSettingCodeMatching(AppActivity context, AttributeSet attrs, DeviceBean deviceBean, String title) {
        this(context, attrs, 0, deviceBean, title);
    }

    public DeviceSettingCodeMatching(AppActivity context, AttributeSet attrs, int defStyleAttr, DeviceBean deviceBean, String title) {
        this(context, attrs, defStyleAttr, R.style.setting_item_style, deviceBean, title);
    }

    public DeviceSettingCodeMatching(@NonNull AppActivity context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes, DeviceBean deviceBean, String title) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mDevice = deviceBean;
        mContext = context;
        setLeftText(title);
        setRightTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
        //1-成功 0-失败 2-初始化
        String rightText = null;
        Integer cm_result = mDevice.getStateData().getSettings().getCm_result();
        if(cm_result == 0){
            rightText = getResources().getString(R.string.matched_code);
        }else{
            rightText = getResources().getString(R.string.not_matching_code);
        }
        setRightText(rightText);
        setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        setRightTextSize(COMPLEX_UNIT_PX, DensityUtils.dip2px(context, 12));
        setOnClickListener(this::onClick);
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;
    private void showDialog() {
        if(mConfirmHintDialog == null){
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getContext());
            mConfirmHintDialogBuilder.setLeftBtnText(getResources().getString(R.string.cancel));
            mConfirmHintDialogBuilder.setRightBtnText(getResources().getString(R.string.start_match_code));
            mConfirmHintDialogBuilder.setContent(getResources().getString(R.string.code_matching_hint));
            mConfirmHintDialogBuilder.setListener(new ConfirmHintDialog.OnListener() {
                @Override
                public void onLeftClick(BaseDialog dialog) {
                    dialog.dismiss();
                }

                @Override
                public void onConfirm(BaseDialog dialog) {
                    dialog.dismiss();
                    matchCode();
                }
            });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialog.show();
    }

    private Runnable countRunnable = new Runnable() {
        @Override
        public void run() {
            if(System.currentTimeMillis() - startTime > totalTime){
                handleFailed();
            }else{
                postDelayed(this, 990);
            }
        }
    };

    private void matchCode(){
        startTime = System.currentTimeMillis();
        post(countRunnable);
        Map<String, Object> stateData = new HashMap<>();
        Map<String, Object> settings = new HashMap<>();
        settings.put("codematch", 1);
        stateData.put("settings", settings);
        LLHttpManager.sendDeviceSetting(mContext, mDevice.getDeviceSerialNo(), stateData, new HttpCallback<HttpData<QueryCodeResultBean<String, Object>>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity)getContext()).showDialog(getResources().getString(R.string.matching_code));
                }
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<String, Object>> result) {
                getHandler().postDelayed(pollingRunnable, 1000);
            }

            @Override
            public void onFail(Exception e) {
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {

            }
        });
    }

//    private void querySendDeviceSetting(){
//        LLHttpManager.querySendDeviceSetting(mContext, queryCode, new HttpCallback<HttpData<QueryCodeResultBean<String, Object>>>(null){
//            @Override
//            public void onStart(Call call) {
//            }
//
//            @Override
//            public void onSucceed(HttpData<QueryCodeResultBean<String, Object>> result) {
//                handleResult(result.getData());
//            }
//
//            @Override
//            public void onFail(Exception e) {
//                super.onFail(e);
//                handleFailed();
//            }
//
//            @Override
//            public void onEnd(Call call) {
//            }
//        });
//    }
//
//    private void handleResult(QueryCodeResultBean data){
//        queryCode = data.getQueryCode();
//        //发起操作:0 正在操作:1 操作成功:2 操作失败:3 操作异常:4 停止操作:5
//        if(data != null){
//            switch (data.getQueryStateType()){
//                case 0:
//                case 1:
//                    getHandler().postDelayed(pollingRunnable, 1000);
//                    break;
//                case 2:
//                    ToastUtils.show(R.string.matching_code_success);
//                    break;
//                case 3:
//                case 4:
//                case 5:
//                    handleFailed();
//                    break;
//            }
//        }
//    }

    private void querySendDeviceSetting(){
        LLHttpManager.getDeviceItem(mContext, mDevice.getDeviceSerialNo(), new HttpCallback<HttpData<List<DeviceBean>>>(null){
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<List<DeviceBean>> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {
            }
        });
    }

    private void handleResult(List<DeviceBean> data) {
        DeviceBean device = data.get(0);
        //0-成功 1-失败 2-初始化
        switch (device.getStateData().getSettings().getCm_result()){
            case 0:
                getHandler().removeCallbacksAndMessages(null);
                ToastUtils.show(R.string.matching_code_success);
                hideDialog();
                break;
//            case 1:
//                handleFailed();
//                break;
//            case 2:
            default:
                getHandler().postDelayed(pollingRunnable, 1000);
                break;
        }
    }

    private void handleFailed(){
        getHandler().removeCallbacksAndMessages(null);
        ToastUtils.show(R.string.matching_code_failed);
        hideDialog();
    }

    private Runnable pollingRunnable = new Runnable(){
        @Override
        public void run() {
            querySendDeviceSetting();
        }
    };

    private void hideDialog(){
        if(getContext() != null && getContext() instanceof AppActivity){
            ((AppActivity)getContext()).hideDialog();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getHandler().removeCallbacksAndMessages(null);
    }

    @Override
    public void onClick(View v) {
        showDialog();
    }
}
